package com.abing.permissionsys.controller;

import com.abing.base.BaseResponse;
import com.abing.core.utils.EncryptUtils;
import com.abing.permissionsys.entity.ImgResult;
import com.abing.permissionsys.entity.req.LoginReq;
import com.abing.permissionsys.log.aop.Log;
import com.abing.permissionsys.security.security.AuthenticationInfo;
import com.abing.permissionsys.security.security.JwtUser;
import com.abing.permissionsys.security.utils.JwtTokenUtil;
import com.abing.permissionsys.security.utils.VerifyCodeUtils;
import com.abing.twitter.SnowflakeIdUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.*;
import cn.hutool.core.codec.Base64;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

@RestController
public class LoginController extends BaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

//    @GetMapping(value = "/initEnumList")
//    BaseResponse index(Model model) {
//        Map<String, Object> map = new HashMap<String, Object>();
//        map.put("enum_status", enumService.getEnumList("STATUS"));
//        return setResultSuccess(map);
//    }


    @Autowired
    @Qualifier("jwtUserDetailsService")
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Log("用户登录")
    @PostMapping("/login")
    @ResponseBody
    BaseResponse login(@RequestBody LoginReq loginReq, HttpServletRequest request) {

        try {
//            //从session中获取验证码
//            String verifyCode = (String) request.getSession().getAttribute(loginReq.getUuid());
//            if (StringUtils.isBlank(verifyCode)) {
//                return setResultError("验证码过期");
//            }
//            if (!verifyCode.toLowerCase().equals(loginReq.getCode().toLowerCase())) {
//                return setResultError("请输入正确的验证码");
//            }
//            request.getSession().removeAttribute(loginReq.getUuid());
        } catch (Exception e) {
            logger.error("验证码校验失败", e);
            return setResultError("验证码校验失败");
        }
        final JwtUser jwtUser = (JwtUser) userDetailsService.loadUserByUsername(loginReq.getUsername());
        if(!jwtUser.getPassword().equals(EncryptUtils.encryptMD5(loginReq.getPassword()))){
            throw new AccountExpiredException("密码错误");
        }

        if(!jwtUser.isEnabled()){
            throw new AccountExpiredException("账号已停用，请联系管理员");
        }

        // 生成令牌
        final String token = jwtTokenUtil.sign(jwtUser);

        return setResultSuccess(new AuthenticationInfo(token,jwtUser));
    }
    /**
     * 获取用户信息
     * @return
     */
    @GetMapping(value = "/getUserInfo")
    public ResponseEntity getUserInfo(){
        JwtUser jwtUser = (JwtUser)userDetailsService.loadUserByUsername(getUsername());
        return ResponseEntity.ok(jwtUser);
    }
    @GetMapping("/logout")
    BaseResponse logout() {
        return setResultSuccess();
    }
    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    @ResponseBody
    public ImgResult getVerify(HttpServletRequest request)throws IOException {
        //生成随机字串
        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
        String uuid = SnowflakeIdUtils.nextId();
        request.getSession().setAttribute(uuid,verifyCode);
        // 生成图片
        int w = 111, h = 36;
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(w, h, stream, verifyCode);
        try {
            return new ImgResult(Base64.encode(stream.toByteArray()),uuid);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            stream.close();
        }
    }

}

